uniform sampler2D textMap;

void main()
{
	vec4 baseColour = vec4(0, 0, 1, 1);
	baseColour.a = texture2D(textMap, gl_TexCoord[0].xy).a;
	float distanceFactor = baseColour.a;
	
	float width = fwidth(gl_TexCoord[0].x) * 25.0; // 25 is an arbitrary scale factor to get an appropriate width for antialiasing
	baseColour.a = smoothstep(0.5-width, 0.5+width, baseColour.a);
	
	// Outline constants
	const vec4 outlineColour = vec4(1, 1, 1, 1);
	const float OUTLINE_MIN_0 = 0.4;
	float OUTLINE_MIN_1 = OUTLINE_MIN_0 + width * 2;
	const float OUTLINE_MAX_0 = 0.5;
	float OUTLINE_MAX_1 = OUTLINE_MAX_0 + width * 2;
	
	// Outline calculation
	if (distanceFactor > OUTLINE_MIN_0 && distanceFactor < OUTLINE_MAX_1)
	{
		float outlineAlpha;
		if (distanceFactor < OUTLINE_MIN_1)
			outlineAlpha = smoothstep(OUTLINE_MIN_0, OUTLINE_MIN_1, distanceFactor);
		else
			outlineAlpha = smoothstep(OUTLINE_MAX_1, OUTLINE_MAX_0, distanceFactor);
			
		baseColour = mix(baseColour, outlineColour, outlineAlpha);
	}
	
	
	// Shadow / glow constants
	const vec2 GLOW_UV_OFFSET = vec2(-0.004, -0.004);
	const vec3 glowColour = vec3(0, 0, 0);
	
	// Shadow / glow calculation
	float glowDistance = texture2D(textMap, gl_TexCoord[0].xy + GLOW_UV_OFFSET).a;
	float glowFactor = smoothstep(0.3, 0.5, glowDistance);
	
	baseColour = mix(vec4(glowColour, glowFactor), baseColour, baseColour.a);
	
	gl_FragColor = baseColour;
}